/**
 *
 *
 *
 */

var properties = { //REQUIRED
};
var BOI = parent.BOI; //REQUIRED
var BOILib = parent.BOILib; //REQUIRED
properties.executed_reports = [];
var initialize = function initialize() {//REQUIRED //initialization function ... see below..
    refreshProperties();
    init();
};
var refresh = function refresh() { //REQUIRED function to be called by parent at anytime to refresh data.
};
var refid = undefined;
var refreshProperties = function refreshProperties() { //REQUIRED function to be called by parent when a property change occurs
    properties.executed_reports = [];
    properties.current_report = undefined;
    properties.text = "original";
};
// absolute url for ZBI_INTEGRATION
var url_bw_root_zbi = BOILib.Util.getBaseUrlBWAbap()+'zbi_integration/';

function openReportGrp(report) {
    parent.BOIData.read.getNode(BOI.app_id, report.id, function (data) {
        //edit by abdulmajeed start...
        if ($('#' + activeTab).find('[LOC]').length == 0) {
            //added by Abdulmajeed to enable dynamic layout for report group...
            if ($(data).find('REPORTS_LAYOUT').find("dynamic").get(0)) {
                var numCols = $(data).find('REPORTS_LAYOUT').find("dynamic").attr('cols');
                var podHeight = $(data).find('REPORTS_LAYOUT').find("dynamic").attr('podHeight');
                // the layout is dynamic and  need to render the components
                // in the dynamic layout
                /*var dynamicLayout = $('<iframe frameborder="0" src="dynamicLayout.htm"></iframe>');

                 dynamicLayout.load(function()
                 {
                 if(this.contentWindow.document.readyState == "complete")
                 {
                 //this.contentWindow.reportsList = report.reports;
                 this.contentWindow.loadDynamicLayout(report.reports, numCols, function()
                 {
                 $('#' + activeTab).removeClass('loading');
                 //openSubReports(report);
                 });
                 }
                 });*/

                var locations = {}; //hashset of locations
                var replocs = $(data).find('LAYOUT_INFO REPORTS_LOC').text();
                replocs = replocs.split('|');
                for (var i in replocs) {
                    if (replocs[i]) {
                        var pcs = replocs[i].split('=');
                        if (pcs.length == 2) {
                            locations[pcs[0]] = pcs[1];
                            rep_def = $(data).find('REP_DEFINITION').text();
                            var loc_icon_txt = undefined;
                            if (rep_def !== undefined) {
                                loc_icon_txt = $(rep_def).find("ICON[LOC='" + pcs[1] + "']").text();
                                if (loc_icon_txt == undefined || loc_icon_txt == '') {
                                    loc_icon_txt = $(rep_def).find("ICON[LOC='ALL']").text();
                                }
                                locations[pcs[0]] = loc_icon_txt;
                            }
                        }
                    }
                }

                var subReportWidth;
                var subReportHeight;

                var outerHt = $('.tab-content-inner').height();
                var dynamicLayout = $('<ul id="dynamicContainer"  class="kpi-container">');
                var locationIndex = 0;

                /*dynamicLayout.height(outerHt - 10);

                 $('.tab-content-inner').resize(function() {
                 dynamicLayout.height(outerHt - 10);
                 });

                 $('window').resize(function() {
                 dynamicLayout.height(outerHt - 10);
                 });*/

                var numReports = 0;
                $.each(report.reports, function (key, value) {
                    numReports++;
                });

                var numRows = Math.ceil(numReports / numCols);

                if (numReports == 1) {
                    subReportWidth = '99%';
                    subReportHeight = '99%';
                }
                else if (numReports == 2) {
                    subReportWidth = '99%';
                    subReportHeight = '48%';
                }
                else {
                    if (numReports == numCols) {
                        numCols = Math.ceil(numCols / 2);
                    }

                    subReportHeight = podHeight;
                    subReportWidth = ((100 / numCols) - 1.5) + '%';
                }
                $.each(report.reports, function (key, value) {
                    reportItem = $('<div class="kpi_view" loc="' + locationIndex + '" rep_id="' + this.tech_name + '"></div>');

                    //var kpiView = $('<div class="" rep_id="'+ this.tech_name +'"></div>');
                    reportItem.append($(createiconhtml(locations[this.tech_name])));

                    reportItem.find('.toolbar span').text(this.label);

                    var placeholder = '<iframe style="height:100%" loc="' + locationIndex + '" name="rep_' + this.tech_name + '"></iframe>';
                    if (this.type == parent.BOILib.ReportTypes.KPI) {
                        placeholder = '<iframe style="height:100%" loc="' + locationIndex + '" src="' + BOI.kpiURL + '" name="rep_' + this.tech_name + '"></iframe>';
                    }

                    var kpiCover = reportItem.find('.kpi-cover');
                    kpiCover.append(placeholder);
                    //reportItem.append(kpiView);


                    var reportItemList = $('<li loc="' + locationIndex + '" class="kpi-list-item-show" ></li>');
                    reportItemList.css(
                        {
                            width:subReportWidth,
                            height:subReportHeight
                        });

                    reportItemList.append(reportItem);
                    dynamicLayout.append(reportItemList);

                    locationIndex++;
                });

                BOI.Events.addListener(BOI.Events.resize, function (args) {
                    var location = args[0];
                    var max_a = $('#' + activeTab).find('[LOC="' + location + '"] a.resize');
                    var title = max_a.attr('title');
                    if (title != "Maximize") {
                        var kpiListItem = $('#' + activeTab).find('li[LOC="' + location + '"]');
                        kpiListItem.css(
                            {
                                width:'99%',
                                height:'99%'
                            });
                    }
                    else {
                        $('#' + activeTab).find('li.kpi-list-item-show').css(
                            {
                                width:subReportWidth,
                                height:subReportHeight
                            });
                    }
                });

                $('#grp_' + report.id).append(dynamicLayout);
            }
            else {
                $('#grp_' + report.id).html(loadLayout(data));
            }
        }
        //open the child reports
        //for (var i in report.reports) {
        $.each(report.reports, function (key, value) {
            //var rep = report.reports[i];
            var rep = this;
            //kpis
            if (rep.type == parent.BOILib.ReportTypes.KPI) {
                var iframeComp = $("[name='rep_" + rep.tech_name + "']");
                // Check if iframe is already loaded
                if(rep.content_loaded){ //iframe already loaded - run executeReport again with new variables
                    var name =  iframeComp.attr('name');
                    var loc =  iframeComp.attr('loc');
                    loadKpiData(rep, name, loc, iframeComp[0]);
                }
                else { // load iframe for first time
                    iframeComp.load(function () {
                        loadKpiData(rep, $(this).attr('name'), $(this).attr('loc'), this);
                    });
                }
            }
            else if (rep.type == "FLASH" || rep.type == "BO_DASHBOARD" || rep.type == "BW_DASHBOARD") {
                BOI.openReport(rep.id, rep.type, undefined, true, 'rep_' + rep.tech_name, true, function () {
                }, document);
            }
            else {
                BOI.openReport(rep.id, rep.type, undefined, true, 'rep_' + rep.tech_name, true, function () {
                    BOI.Events.raiseEvent(BOI.Events.repchange, [report.id]);
                });
            }
        });
    });
}
//edit by abdulmajeed end...

//edit by Sefuvan to loadKPIdata on iframe load and update iframe content on varchange
function loadKpiData(rep, name, loc, iframe){
    if (iframe)
        if (iframe.contentWindow.document.readyState == "complete") {
            var kpi = { X_AXIS:'', Y_AXES:{}, SERIES_AXIS:'', CHART_TYPE:'Line', DRILL_DOWNS:{} };
            BOI.loadReportMeta(rep, function (report) { //name.substr(4),
                //parent.BOIData.read.getNode(BOI.app_id, name.substr(4), function (kpi_def_data) {
                kpi_def_data = $(report.metadata);
                //kpi_def_data = $(kpi_def_data);
                var drilldown = kpi_def_data.find('KPI_DRL_DOWN_URL').text();
                if (drilldown.length == 0) drilldown = "#";
                //set kpi values
                var definition = kpi_def_data.find('REP_DEFINITION').text();
                // Ansaj edited for setting data_provider in rep
                rep.data_provider = kpi_def_data.find('DATA_PROVIDER').text();
                definition = $(definition);
                kpi.X_AXIS = definition.find('X_AXIS').text();
                kpi.SERIES_AXIS = definition.find('SERIES_AXIS').text();
                kpi.PLOT_TYPE = definition.find('PLOT_TYPE').text();
                kpi.CHART_TYPE = definition.find('CHART_TYPE').text();
                kpi.MAXIMUM = definition.find('MAXIMUM').text();

                //Abdulmajeed Edit Start ... extra configurations for KPI...
                kpi.LABEL_POSITION = definition.find('LABEL_POSITION').text();
                kpi.X_AXIS_LABEL = definition.find('X_AXIS_LABEL').text();
                kpi.Y_AXIS_LABEL = definition.find('Y_AXIS_LABEL').text();
                kpi.X_DECIMAL_POSITION = definition.find('X_DECIMAL_POSITION').text();
                kpi.Y_DECIMAL_POSITION = definition.find('Y_DECIMAL_POSITION').text();

                if(definition.find('COLOR_RANGES'))
                {
                    var colorRangesXML = definition.find('COLOR_RANGE');
                    kpi.COLOR_RANGES = new Array();
                    colorRangesXML.each(function(key, value)
                    {
                        kpi.COLOR_RANGES[key] = new Object();
                        kpi.COLOR_RANGES[key].FROM_VALUE = $(this).attr('FROM');
                        kpi.COLOR_RANGES[key].TO_VALUE = $(this).attr('TO');
                        kpi.COLOR_RANGES[key].COLOR_CODE = $(this).attr('COLOR_CODE');

                    });
                }

                kpi.SCALE_TYPE = definition.find('SCALE_TYPE').text();
                kpi.SCALE_MODE = definition.find('SCALE_MODE').text();
                //Abdulmajeed Edit End ... extra configurations for KPI...

                kpi.DRILL_DOWNS = {};
                definition.find('Y_AXES Y_AXIS').each(function () {
                    kpi.Y_AXES[$(this).text()] = $(this).text();
                });
                // otaism2a : 9/2/2014 added to reduce the line of code for kpi loading
                kpi.DRILL_DOWNS = new Array();
                kpi.DRILL_DOWNS = BOI.loadKpiDrillDown(definition, kpi);

                //get data
                //01-22-14 change by abdulmajeed, add argument to get key text.
                var queryArguments = new Object();
                queryArguments['display_key'] = 'X';

                parent.BOI.executeReport(rep, "", function (kpi_data) {
                    iframe.contentWindow.properties.data = kpi_data;
                    iframe.contentWindow.properties.kpi = kpi;
                    iframe.contentWindow.properties.location = parseInt(loc);
                    iframe.contentWindow.properties.drill = drilldown;
                    iframe.contentWindow.properties.current_report = rep;
                    iframe.contentWindow.initialize();

                    // Set Scrollbar postion to Top - faisal
                    $('ul.kpi-container').scrollTop(0);
                }, queryArguments);

                rep.content_loaded=true;
            });

        }
    $('#' + activeTab).removeClass('loading');
}
//edit by Sefuvan end...
function openReport(report) {

    if (BOI.DrillSpec.drillReportVisible) {
        BOI.DrillSpec.goBack();
    }
    if (report.id == properties.current_report.id) {
        if (report.type == parent.BOILib.ReportTypes.ReportGroup) {
            openReportGrp(report);
        }
        else if ((report.type == "FLASH" || report.type == "BO_DASHBOARD" || report.type == "BW_DASHBOARD")) {
            $('#' + activeTab).addClass('loading');
            BOI.openReport(properties.current_report.id, properties.current_report.type, undefined, true, properties.current_report.id, true, function () {
                BOI.Events.raiseEvent(BOI.Events.repchange, [report.id]);
            }, document);
        }
        else {
            $('#' + activeTab).addClass('loading');
            BOI.openReport(properties.current_report.id, properties.current_report.type, undefined, true, properties.current_report.id, true, function () {
                BOI.Events.raiseEvent(BOI.Events.repchange, [report.id]);
            });
        }
        properties.current_report.state = BOILib.ReportStates.Executed;
        BOI.context.reports[properties.current_report.id].state = BOILib.ReportStates.Executed;
    }
}

function getKPITechnicalName(button) {
    var containerDiv = button.parents('[LOC]').children('[rep_id]').attr("rep_id");
    if (containerDiv != undefined) {
        return containerDiv;
    }
    return undefined;
}
function getKPIType(buttonHldr) {
    var chart_type = buttonHldr.attr("view_type");

    if (chart_type === undefined) {
        chart_type = "Summary";
    }
    return chart_type;
}
function toggleKPIType(buttonHldr) {
    var chart_type = buttonHldr.attr("view_type");

    if (chart_type === undefined) {
        chart_type = "Summary";
    }

    if (chart_type == "Summary") {
        chart_type = "Detail";
    }
    else {
        chart_type = "Summary";
    }

    buttonHldr.attr("view_type", chart_type);
    return chart_type;
}

function checkStatusAndExecute(report) {
    if (report) {
        if (report.state == "refresh") {

            if (!report.metadata) {
                BOI.loadReportMeta(report, function (meta) {
                    checkStatusAndExecute_Internal(report);
                });
            }
            else {
                checkStatusAndExecute_Internal(report);
            }


        }
        else //report is already open
        {
            BOI.Events.raiseEvent(BOI.Events.repchange, [report.id]);
            // if (report.state == "executed"){
            //      openReport(report);
            // }
            // Add the condition for displaying the report in new window
            if (report.OPEN_STYLE == "_BLANK") {
                openReport(report);
                return;
            }
            // Add for hide
            if ((report.type == 'BO_CRYSTAL' || report.type == 'URL' ) && report.tech_name != "ADMIN_PAGE" && report.url.indexOf(".pdf") == -1 && report.url.indexOf(".PDF") == -1) {
                $("#bi_comment").css("display", "block");
            }
            else {
                $("#bi_comment").css("display", "none");
            }
            //Add for hide ends here
            toggleView('tabs');
            //$('#dialog').hide();
        }
    }
}

function checkStatusAndExecute_Internal(report) {
    var execute = true;
    var show_variable = false;
    var isvariable = varExist()
    //report.VARIABLE_SCREEN
    if (isvariable > 0 && report.metadata) {
        // find the list of variables in metadata
        var var_list = $(report.metadata).find('LAYOUT_INFO VAR_LIST');
        report.varlayout = $(report.metadata).find('VARIABLES_LAYOUT').text();
        if (var_list) {
            if (var_list.text() != '') { // if variable is available in variable screen
                for (var i in report.variables) {
                    var repvar = report.variables[i];
                    if (repvar.ENTRYTP == "1" && repvar.value == "") {//MANDATORY
                        show_variable = true;
                        execute = false;
                        break;
                    }
                    else if (repvar.ENTRYTP == "2" && (repvar.value == repvar.defval || repvar.value == "")) {
                        show_variable = true;
                        execute = false;
                        break;
                    }
                }
            }
        }
    }

    if (execute) {
        openReport(report);
        if (report.VARIABLE_SCREEN == "X" || report.VARIABLE_SCREEN) {
            $("#screen_id").get(0).contentWindow.rep_changed = true;
            toggleView('dialog');
        }
        else {
            toggleView('tabs');
        }
    }

    else {
        // this condition is required, for the report to show the
        // variable screen with mandatory variables
        //report.VARIABLE_SCREEN
        if (isvariable > 0 && show_variable) {
            $('#' + activeTab).removeClass('loading');
            //show var screen
            BOI.Events.raiseEvent(BOI.Events.repchange, [report.id]);
            //$('#dialog').show();
            var toggle_stat = toggleView('dialog');
            if (!toggle_stat) {
                openReport(report);
            }
        }
        else {
            // If the report is not having variable screen, then
            // just show the
            openReport(report);
        }
    }
}

//edited by jaroudnh 1/29/2014, this function is specific to mis
//to be deleted...
function createiconhtml_mis(loc_icon_txt) {
    //var iconhtml = undefined;
    var iconhtml = "";
    if (loc_icon_txt == undefined || loc_icon_txt == 'undefined') {
        /* iconhtml =  '<ul>' +
         '<li><a view_type="Summary" class="chart" href="#" title="Chart"><img id="icon_02"  class="icon-swap" width="22" height="22"  src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_02_off.png" /></a></li>' +
         '<li><a  view_type="Table" class="tabular" href="#" title="Table"><img id="icon_01"  class="icon-swap" width="22" height="22" src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_01_off.png" /></a></li>' +
         '<li><a  view_type="Detail" class="url" target="_blank" title="Trend"><img id="icon_03"  class="icon-swap" width="22" height="22" src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_03_off.png" /></a></li>' +
         //  '<li><a class="print"  title="Print"><img width="16" src="img/icon/print.png" /></a></li>' +
         '<li><a class="comment" href="#" title="Comment" ><img id="icon_06"  class="icon-swap" width="22" height="22" src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_06_off.png"  /></a></li>' +
         '<li id="resize_li"><a class="resize" href="#" title="Maximize"><img id="icon_05" class="min-max-img icon-swap" width="22" height="22"  src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_05_off.png" /></a></li>' +

         '</ul>';
         */
    } else {
        if (loc_icon_txt.toLowerCase().indexOf("all") >= 0 || loc_icon_txt == undefined || loc_icon_txt == '') {
            /*
             iconhtml =  '<ul>' +
             '<li><a view_type="Summary" class="chart" href="#" title="Chart"><img  id="icon_02" class="icon-swap" width="22" height="22"  src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_02_off.png" /></a></li>' +
             '<li><a  view_type="Table" class="tabular" href="#" title="Table"><img  id="icon_01" class="icon-swap" width="22" height="22" src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_01_off.png" /></a></li>' +
             '<li><a  view_type="Detail" class="url" target="_blank" title="Trend"><img  id="icon_03" class="icon-swap" width="22" height="22" src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_03_off.png" /></a></li>' +
             // '<li><a class="print"  title="Print"><img width="16" src="img/icon/print.png" /></a></li>' +
             '<li><a class="comment" href="#" title="Comment" ><img id="icon_06"  class="icon-swap" width="22" height="22" src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_06_off.png"  /></a></li>' +
             //'<li id="min_li"><a class="minimize" href="#" title="Minimize"><img id="min" width="16" src="img/icon/196.png" style="display : none"/></a></li>' +
             '<li id="resize_li"><a class="resize" href="#" title="Maximize"><img id="icon_05" class="min-max-img icon-swap" width="22" height="22"  src="../zbi_integration/'+BOI.theme+'/img/icon/mis_icon_05_off.png" /></a></li>' +

             '</ul>';
             */
        } else {
            iconhtml = '<ul>';
            if (loc_icon_txt.toLowerCase().indexOf("chart") >= 0) {
                iconhtml = iconhtml + '<li><a view_type="Summary" class="chart" href="#" title="Chart"><img id="icon_02" class="icon-swap" width="22" height="22"  src="'+ url_bw_root_zbi + BOI.theme + '/img/icon/mis_icon_02_off.png" /></a></li>';

            }
            if (loc_icon_txt.toLowerCase().indexOf("table") >= 0) {
                iconhtml = iconhtml + '<li><a  view_type="Table" class="tabular" href="#" title="Table"><img id="icon_01" class="icon-swap" width="22" height="22" src="'+ url_bw_root_zbi + BOI.theme + '/img/icon/mis_icon_01_off.png" /></a></li>';
            }
            if (loc_icon_txt.toLowerCase().indexOf("detail") >= 0) {
                iconhtml = iconhtml + '<li><a  view_type="Detail" class="url" target="_blank" title="Trend"><img id="icon_03" class="icon-swap" width="22" height="22" src="'+ url_bw_root_zbi + BOI.theme + '/img/icon/mis_icon_03_off.png" /></a></li>';
            }
            //  if(loc_icon_txt.toLowerCase().indexOf("print") >= 0){
            //     iconhtml = iconhtml + '<li><a class="print"  title="Print"><img width="16" src="img/icon/print.png" /></a></li>';
            // }
            //if(loc_icon_txt.toLowerCase().indexOf("min") >= 0){
            //  iconhtml = iconhtml + '<li id="min_li"><a class="minimize" href="#" title="Minimize"><img id="min" width="16" src="img/icon/196.png" style="display : none"/></a></li>';
            // }
            if (loc_icon_txt.toLowerCase().indexOf("com") >= 0) {
                iconhtml = iconhtml + '<li><a class="comment" href="#" title="Comment" ><img id="icon_06" class="icon-swap" width="22" height="22" src="'+ url_bw_root_zbi + BOI.theme + '/img/icon/mis_icon_06_off.png"  /></a></li>';
            }
            if (loc_icon_txt.toLowerCase().indexOf("max") >= 0) {
                iconhtml = iconhtml + '<li id="max_li"><a class="resize" href="#" title="Maximize"><img id="icon_05" class="min-max-img icon-swap" id="max" width="22" height="22"  src="'+ url_bw_root_zbi + BOI.theme + '/img/icon/mis_icon_05_off.png" /></a></li>';
            }

            // if(loc_icon_txt.toLowerCase().indexOf("min") >= 0){
            //   iconhtml = iconhtml + '<li><a class="minimize" href="#" title="Minimize"><img width="16" src="img/icon/196.png" /></a></li>';
            //}
            // if(loc_icon_txt.toLowerCase().indexOf("max") >= 0){
            //    iconhtml = iconhtml + '<li><a class="maximize" href="#" title="Maximize"><img width="16"  src="img/icon/195.png" /></a></li>';
            //}

            iconhtml = iconhtml + '</ul>';
        }
    }
    iconhtml = '<span class="toolbar">' + iconhtml + '<span class="clear"></span>' + '</span><div class="kpi-cover"></div>';
    return iconhtml;
}

//Added by jaroudnh, to have click functionality on each icon on the toolbar
$('.tb').live('click', function (e) {
    var tech_name = getKPITechnicalName($(this));
    if (tech_name != undefined) {
        var sel_rep = BOI.getContextReportByTechname(tech_name);
        if (sel_rep != undefined) {
            parent.BOI.Events.raiseEvent("toolbar", [sel_rep, document, e, $(this)]);
        }
    }

});

//added by jaroudnh 1/29/2014, this function is public for any dashboard
var registeredFunctions = null;
function createiconhtml(loc_icon_txt) {
    if (registeredFunctions == null);
    registeredFunctions = new Object();
    var iconhtml = "";
    if (loc_icon_txt == undefined || loc_icon_txt == 'undefined') {
        //do nothing
    }
    else if (loc_icon_txt.toLowerCase().indexOf("all") >= 0 || loc_icon_txt == undefined || loc_icon_txt == '') {
        //do nothing
    }
    else {
        iconhtml = '<ul>';

        var icons = loc_icon_txt.toLowerCase().split("-");
        for (var i in icons) {
            if (icons[i] == 'max') {
                iconhtml += '<li><a class="resize" title="Maximize" href="#">' +
                    '<img id="icon_05" class="min-max-img icon-swap" src="' + url_bw_root_zbi + BOI.theme + '/img/icon/toolbar/{0}.png" width="22" height="22">' +
                    '</a></li>';
            }

            else {
                iconhtml +=
                    '<li>' +
                        '<a class="report_view" href="#" title="{1}">' +
                        '<img class="tb" iconname="{0}" width="22" height="22" src="' + url_bw_root_zbi + BOI.theme + '/img/icon/toolbar/{0}.png" />' +
                        '</a>' +
                        '</li>';
            }
            iconhtml = replaceAll("{0}", icons[i], iconhtml);
            iconhtml = replaceAll("{1}", icons[i], iconhtml);

        }
        iconhtml = iconhtml + '</ul>';
    }
    iconhtml = '<span class="toolbar">' + iconhtml + '<span class="clear"></span>' + '</span><div class="kpi-cover"></div>';
    return iconhtml;
}

//Added by jaroudnh on 1/29/2014
function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
//Added by jaroudnh on 1/29/2014
function replaceAll(find, replace, str) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

function loadLayout(data) {
    data = $(data);
    var layout = $(data).find('REPORTS_LAYOUT');
    var locations = {}; //hashset of locations
    var replocs = $(data).find('LAYOUT_INFO REPORTS_LOC').text();
    replocs = replocs.split('|');
    for (var i in replocs) {
        if (replocs[i]) {
            var pcs = replocs[i].split('=');
            if (pcs.length == 2) {
                locations[pcs[0]] = pcs[1];
                rep_def = $(data).find('REP_DEFINITION').text();
                var loc_icon_txt = undefined;
                if (rep_def !== undefined) {
                    loc_icon_txt = $(rep_def).find("ICON[LOC='" + pcs[1] + "']").text();
                    if (loc_icon_txt == undefined || loc_icon_txt == '') {
                        loc_icon_txt = $(rep_def).find("ICON[LOC='ALL']").text();
                    }
                }
                layout.find('[LOC=' + pcs[1] + ']').html(createiconhtml(loc_icon_txt));
            }
        }
    }
    //read reports and assign them to corresponding positions in layout
    $(data).find('REPORTS REPORT').each(function () {

        var name = $(this).find('TECH_NAME').text().trim();
        var report = BOI.getContextReportByTechname(name);
        var title = $(this).find('TITLE').text().trim();
        var desc = $(this).find('DESCRIPTION').text().trim();
        var loc = "";
        if (locations[name]) {
            loc = locations[name];
        }
        var placeholder = '<iframe style="height:100%" loc="' + loc + '" name="rep_' + name + '"></iframe>';
        if (report.type == parent.BOILib.ReportTypes.KPI) {
            placeholder = '<iframe style="height:100%" src="' + BOI.kpiURL + '" loc="' + loc + '" name="rep_' + name + '"></iframe>';
        }
        var item = layout.find('*[LOC="' + loc + '"] div');
        item.append(placeholder);
        item.attr('REP_ID', name);
    });
    var html = layout.html();
    return html;
}
function setReportStateExecuted(report_id) {
    // 1. if there is something in current report, change the staus
    //          to "executed" and save this report to executed_report
    if (properties.current_report) {
        if (properties.current_report.id != report_id) {
            properties.executed_reports[properties.current_report.id] = properties.current_report;
            properties.current_report = BOI.context.reports[report_id];
            properties.executed_reports[report_id] = properties.current_report;
        }

    }
    else {
        // 2. now change the current report to new report
        properties.current_report = BOI.context.reports[report_id];
        properties.executed_reports[report_id] = properties.current_report;

    }
}

function resetReport(report) {
    // 1. if there is something in current report, change the staus
    //          to "executed" and save this report to executed_report
    BOI.context.reports[report.id].state = BOILib.ReportStates.RefreshNeeded;

    //Remove Report ID from the Array by Faisal
    //properties.executed_reports[report.id] = undefined;

    delete properties.executed_reports[report.id];
    properties.current_report = undefined;

    BOI.Flash.removeReportGroup(report, document);

    //reset KPI report iframe content_loaded flag for reportgroup
    resetKpiContentLoadedFlag(report);
}
/**
 * This is for KPI report
 * 'content_loaded' flag will be set TRUE when report iframe content is loaded
 * Need to reset to FALSE onClose of tab
 * @param report
 */
function resetKpiContentLoadedFlag(report){
    if(report.type === "REPORT_GROUP"){
        for (var i in report.reports) {
            var rep = report.reports[i];
            if (rep.type == BOILib.ReportTypes.KPI) {
                rep.content_loaded = false;
            }
        }
    }
    else{
        if (report.type == BOILib.ReportTypes.KPI) {
            report.content_loaded = false;
        }
    }
}

$('.resize').live('click', function () {
    parent.BOI.Events.raiseEvent(parent.BOI.Events.resize, [$(this).parents('[LOC]').attr('LOC')]);

    //$("#max_li").show();
    // $("#min_li").hide();
    // $("#min").css("display" ,"none");
    // $("#max").css("display" ,"block");
});

//$('.maximize').live('click', function () {
//  parent.BOI.Events.raiseEvent(parent.BOI.Events.maximize, [$(this).parents('[LOC]').attr('LOC')]);


// $("#max_li").hide();
//$("#min_li").show();
// $("#min").css("display" ,"block");
// $("#max").css("display" ,"none");
//});

//commented by jaroudnh on 2/27/2014
/*
 $('.tabular').live('click', function () {
 //BOI.Events.raiseEvent(BOI.Events.toolbar, ["aaaa", "bbbbb"]);
 //var location  = $(this).parents('[LOC]').attr('LOC')

 var tech_name = getKPITechnicalName($(this));
 if (tech_name != undefined) {
 // Xcelsius Component
 var sel_rep = BOI.getContextReportByTechname(tech_name);
 if (sel_rep != undefined) {
 if (document.getElementById(sel_rep.id)) {
 var chart_type = getKPIType($(this));
 //toggleKPIType($(this));
 BOI.Flash.sendEIC(sel_rep, "view_type", chart_type, document);
 }
 }


 }


 });
 // for Chart type
 $('.chart').live('click', function () {
 //var location  = $(this).parents('[LOC]').attr('LOC')

 var tech_name = getKPITechnicalName($(this));
 if (tech_name != undefined) {
 // Xcelsius Component
 var sel_rep = BOI.getContextReportByTechname(tech_name);
 if (sel_rep != undefined) {
 if (document.getElementById(sel_rep.id)) {
 var chart_type = getKPIType($(this));
 //toggleKPIType($(this));
 BOI.Flash.sendEIC(sel_rep, "view_type", chart_type, document);
 }
 }


 }


 });
 */


// for url type
$('.url').live('click', function () {
    //var location  = $(this).parents('[LOC]').attr('LOC')
    var tech_name = getKPITechnicalName($(this));
    if (tech_name != undefined) {
        // Xcelsius Component
        var sel_rep = BOI.getContextReportByTechname(tech_name);
        if (sel_rep != undefined) {
            if (document.getElementById(sel_rep.id)) {
                var chart_type = getKPIType($(this));
                //toggleKPIType($(this));
                BOI.Flash.sendEIC(sel_rep, "view_type", chart_type, document);
            }
        }
        // TODO:: KPI Component
        /*$('#chart_placeholder').toggle();
         $('#table_placeholder').toggle();*/

    }


});
$('.print').live('click', function () {
    //onclick="chart.printChart();"
});


//$('.comment').live('mouseenter', function() {
//});
//$('#dialog').width($('body').width() - 100);
//$('#dialog').height($('body').height() - 100);
$('#dialog').find('iframe').each(function () {
    $(this).width('100%');
    $(this).height('100%');
});
//toggler Ansaj made changes for variable screen toggling
$('#toggle,#bi_var_scr').live("click", function () {

    // if (Object.keys(BOI.getContextReport($('#tabs li:eq(' + $("#tabs").tabs("option", "active") + ')').attr("rep_id")).variables).length>0)
    var varacount = varExist();

    if (varacount > 0)
    //  if((BOI.getContextReport($('#tabs li:eq(' + $("#tabs").tabs("option", "active") + ')').attr("rep_id"))).VARIABLE_SCREEN)
    {

        if (($('#dialog').is(':visible') == true)) {  //&& ($('#tab').is(':visible'))

            toggleView('tabs');
            showTitle('hide');
        }
        else {

            //
            toggleView('dialog');
            showTitle('show');
        }
        //  }
    }
    else {
        alert("No Variables are Available");
    }

});
function varExist() {
    var varno = 0;
    // var report = BOI.getContextReport($('#tabs li:eq(' + $("#tabs").tabs("option", "active") + ')').attr("rep_id"));
    var report=properties.current_report;
    for (var dep in BOI.context.reports[report.id].variables) {
        varno++;
    }
    return varno;
}
// toggle between report view and variable screen
function toggleView(view_type) {
    // var report = BOI.getContextReport($('#tabs li:eq(' + $("#tabs").tabs("option", "active") + ')').attr("rep_id"))
    var report=properties.current_report;

    if (view_type == 'tabs') {
        $('#dialog').hide();
        showTitle('hide');
        $("#tabs").show();
    }
    else if (view_type == 'dialog') {
        var varscreen = $("#screen_id").get(0);
        if (varscreen) {
            $("#screen_id").get(0).contentWindow.displayvariable(report);
            $('#dialog').show();
            showTitle('show');
            $('#tabs').hide();

        }
        else {
            // gives the result saying it is not successful in toggling view
            BOI.log += BOILib.Util.log("Variable Screen Cannot be loaded", false);
            return false;
        }
    }
    //toggling is successful
    return true;
}

function showTitle(show_title) {
    if (show_title == 'show') {
        //   var reportname = BOI.getContextReport($('#tabs li:eq(' + $("#tabs").tabs("option", "active") + ')').attr("rep_id")).label;
        var reportname=properties.current_report.label;
        $("#var_screen_title").empty().text();
        //if($('#dialog').is(':visible') == true){

        $("#var_screen_title").append(reportname).text();
        $("#var_screen_title").show();
    }
    else {
        $("#var_screen_title").hide();
    }
}

//Added by jaroudnh on 2/18/2014 to call add to favorites from the favorites component
BOI.Events.addListener("addToFavorites", function (args) {
    addToFavorites();
});

function addToFavorites() {
    //report variables
    var context = "<REPORT_CONTEXT>";
    for (var i in properties.current_report.variables) {
        /*
         * * <REPORT_CONTEXT>
         *     <VARIABLE>
         *         <NAME></NAME>
         *         <SEL_TYPE>M</SEL_TYPE>
         *         <VALUES>
         *           <VALUE></VALUE>
         *           <VALUE></VALUE>
         *         </VALUES>
         *     </VARIABLE>
         * </REPORT_CONTEXT>
         * */
        var variable = properties.current_report.variables[i];
        var vXml = "<VARIABLE><NAME>{n}</NAME><SEL_TYPE>{s}</SEL_TYPE><VALUES>{v}</VALUES></VARIABLE>";
        vXml = vXml.replace('{n}', variable.name);
        vXml = vXml.replace('{s}', variable.seltype);
        if (variable.seltype == BOILib.SelectionTypes.Single) {
            var val = '<VALUE>' + variable.value + '</VALUE>';
            vXml = vXml.replace('{v}', val);
        }
        else //multiple
        {
            var vals = "";
            var val_temp = '<VALUE>{v}</VALUE>';
            for (var i in variable.values) {
                vals += val_temp.replace('{v}', variable.values[i]);
            }
            vXml = vXml.replace('{v}', vals);
        }
        context += vXml;
    }
    context += "</REPORT_CONTEXT>";
    context = parent.BOIData.util.htmlEncode(context);

    //Edited by jaroudnh on 2/9/2014 to add jquery ui dialog...

    BOI.boiPrompt("Adding Report to Favorites", "Please, enter the report name.", properties.current_report.label, function (fav_title) {
        //add to favorites
        var record = parent.BOIData.data.createRecord({ APP_ID:[BOI.app_id], REPORT_ID:[properties.current_report.tech_name], CONTEXT:[context], FAV_TITLE:[fav_title] });
        var req = parent.BOIData.request.prepare("ZCL_MYBW_FAVORITES", "UPDATE", [record]);
        parent.BOIData.request.perform(req, 'text', 'post', function () {
            //reload fav list
            BOI.Events.raiseEvent(BOI.Events.favchange, []);
        });
    }, function () {

    });

    //comminted by jaroudnh on 2/9/2014 to use the new prompt
    /*
     var fav_title = prompt("Enter Favorite Name:", properties.current_report.label);
     //add to favorites
     var record = parent.BOIData.data.createRecord({ APP_ID:[BOI.app_id], REPORT_ID:[properties.current_report.tech_name], CONTEXT:[context], FAV_TITLE:[fav_title] });
     var req = parent.BOIData.request.prepare("ZCL_MYBW_FAVORITES", "UPDATE", [record]);
     parent.BOIData.request.perform(req, 'text', 'post', function () {
     //reload fav list
     BOI.Events.raiseEvent(BOI.Events.favchange, []);
     });
     */
}

//Edited by jaroudnh on 2/18/2014
//favorites
$('#bi_fav_add').live('click', function () {
    addToFavorites();
});

var fid = parent.BOILib.Util.getUrlParam('fid');
if (fid != "") {
    var intervalID = window.setInterval(function () {
        //load the report
        if (BOI.favorites[fid] && BOI.context.reports[fid]) {
            BOI.Events.raiseEvent(BOI.Events.favopen, [fid]);
            clearInterval(intervalID);
        }
    }, 1000);
}

$(function () {
    $(".icon-swap").live('hover', function () {
        if ($(this).attr("class") == "img-swap") {
            this.src = this.src.replace("_off", "_on");
        } else {
            this.src = this.src.replace("_on", "_off");
        }
        $(this).toggleClass("on");
    });


    $(".icon-swap").live("click", function () {
        $(this).closest("ul").find("li").each(function () {
            var srcstr = $(this).find("img").attr("src");
            srcstr = srcstr.replace("_on", "_off");
            $(this).find("img").attr("src", srcstr);
            $(this).find("img").attr("src").replace("_on", "_off");
        });
        var srcstr = $(this).closest("li").find("img").attr("src");
        srcstr = srcstr.replace("_off", "_on");
        $(this).closest("li").find("img").attr("src", srcstr);
    });
});